package org.lixf.thread;

import java.util.concurrent.locks.ReentrantLock;

// ReentrantLock 和 synchronized
// synchronized自动释放锁
// ReentrantLock jdk1.5新增
public class LockTest {
    public static void main(String[] args) {
        Windows1 windows = new Windows1();
        Thread t1 = new Thread(windows);
        Thread t2 = new Thread(windows);
        Thread t3 = new Thread(windows);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}

class Windows1 implements Runnable {

    private int count = 5000;

    private final ReentrantLock lock = new ReentrantLock(true);// 是否公平

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                // 后边的代码是安全的
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName() + " count = " + count);
                    count--;
                } else {
                    break;
                }
            } finally {
                lock.unlock(); // 手动释放锁
            }
        }
    }
}
